import React, { useState } from 'react'
import { TreeSelect, Card, Popover } from 'antd'
const { TreeNode } = TreeSelect

export default () => {
  const [initvalue, setinitvalue] = useState([])

  const onChange = (value: any) => {
    console.log('onChange', value)
    setinitvalue(value)
  }

  const treeData = [
    {
      title: 'Node1',
      value: '0-0',
      key: '0-0',
      children: [
        {
          title: 'Child Node1',
          value: '0-0-0',
          key: '0-0-0',
          children: [
            {
              title: 'Child Node3',
              value: 'wa',
              key: '0-1-0',
              desc: '这是描述内容',
            },
            {
              title: 'Child Node4',
              value: 'z',
              key: '0-1-1',
            },
          ],
        },
      ],
    },
    {
      title: 'Node2',
      value: '0-1',
      key: '0-1',
      children: [
        {
          title: 'Child Node3',
          value: '0-1-0',
          key: '0-1-0',
        },
        {
          title: 'Child Node4',
          value: '0-1-1',
          key: '0-1-1',
        },
      ],
    },
  ]

  const mapData = (data: any = []) => {
    return data.map((item: any) => {
      if (item?.children) {
        return (
          <TreeNode
            value={item?.value}
            key={item?.value}
            title={
              item.desc ? (
                <Popover
                  content={item.desc}
                  title={item.title}
                  placement="right"
                >
                  <div>{item.title}</div>
                </Popover>
              ) : (
                item.title
              )
            }
          >
            {mapData(item.children)}{' '}
          </TreeNode>
        )
      } else {
        return (
          <TreeNode
            value={item?.value}
            key={item?.value}
            title={
              item.desc ? (
                <Popover
                  content={item.desc}
                  title={item.title}
                  placement="right"
                >
                  <div>{item.title}</div>
                </Popover>
              ) : (
                item.title
              )
            }
          ></TreeNode>
        )
      }
    })
  }

  return (
    <Card
      title="Default size card"
      extra={<a href="#">More</a>}
      style={{ width: 600 }}
    >
      <TreeSelect
        showSearch
        style={{ width: 500 }}
        value={initvalue}
        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
        placeholder="Please select"
        allowClear
        multiple
        treeCheckable
        treeDefaultExpandAll
        onChange={onChange}
      >
        {mapData(treeData)}
      </TreeSelect>
    </Card>
  )
}
